package com.crm.dataReceive.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.crm.custinfo.domain.CustCommentRecord;
import com.crm.custinfo.domain.CustInfo;
import com.crm.custinfo.service.ICustCommentRecordService;
import com.crm.custinfo.service.ICustInfoService;
import com.crm.dataReceive.domain.Customer;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.TypeConstant;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.AesUtils;
import com.ruoyi.common.utils.Md5Encrypt;
import com.ruoyi.common.utils.ObjectUtil;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能说明: 分发系统分发数据接收API<br>
 * 开发人员: @author Mr.Wen<br>
 *
 * @date 2023-12-28
 */
@RestController
@RequestMapping("/dataCenter2")
public class DataReceiveNewController extends BaseController {
    public static final org.slf4j.Logger logger = LoggerFactory.getLogger("custApiLog");
    @Autowired
    private ICustInfoService custInfoService;
    @Autowired
    private ICustCommentRecordService custCommentRecordService;

    @Autowired
    private ISysUserService iSysUserService;
    private int code;// code：0 推送成功 code：-1 推送失败
    private String msg; //
    private List<Map<String, Object>> list; // 排重包list

    public List<Map<String, Object>> getList() {
        return list;
    }

    public void setList(List<Map<String, Object>> list) {
        this.list = list;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getResult() {
        Map<String, Object> result = new HashMap<>();
        result.put("code", getCode());
        result.put("msg", getMsg());
        result.put("list", getList());
        return result;
    }

    /**
     * 添加客户
     *
     * @return
     */
    @Anonymous
    @PostMapping("/addCust/tenant/{tenantId}")
    public String addCust() {
        return apply();
    }

    public String apply() {
        try {
            String requestBoday = getRequestBoday();
            JSONObject json = JSONObject.parseObject(requestBoday);
            if (json == null) {
                setCode(-1);
                setMsg("请求包数据为空");
                return JSON.toJSONString(getResult());
            }
            logger.info("分发数据接收API请求参数原文：{}", json);
            String data = json.getString("data");// 加密结果
            // 数据解密key
            String key = "fGYv8HfEdb9cStYn";
            // 数据解密
            String dataStr = AesUtils.decrypt(data, key);
            if (StringUtils.isBlank(dataStr)) {
                setCode(-1);
                setMsg("数据解密异常");
                return JSON.toJSONString(getResult());
            }
            JSONObject req = JSONObject.parseObject(dataStr);
            Customer customer = JSON.toJavaObject(req, Customer.class);
            String city = req.getString("city");
            city = city == null ? "" : city.replace("市", "").replace("地区", "");
            customer.setCity(city);
            customer.setSex(String.valueOf(req.getInteger("sex"))); // 假设性别是1或2
            customer.setMobile(req.getString("phone"));
            customer.setAge(req.getLong("age"));
            customer.setApplyLimit(new BigDecimal(req.getString("getLimit")));
            customer.setApplyTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(req.getString("applyTime")));
            customer.setCustName(req.getString("userName"));


            logger.info("线索接收API请求参数：{}", customer.toString());
            // 是否作为重复数据入库
            int isRepeat = req.getIntValue("isRepeat");
            int count = custInfoService.countByMd5(Md5Encrypt.md5(customer.getMobile()));
            if (count > 0 && isRepeat == 0) {
                setCode(-1);
                setMsg("撞库未通过");
                return JSON.toJSONString(getResult());
            }
            if (count == 0 && isRepeat == 1) {
                // 如果显示是重复入库但实际库中没有，也不算重复标识
                isRepeat = 0;
            }
            CustInfo custInfo = new CustInfo();
            ObjectUtil.copyProperties(customer, custInfo);
            if (custInfo.getApplyTime() == null) {
                custInfo.setApplyTime(new Date());
            }
            custInfo.setMd5val(Md5Encrypt.md5(custInfo.getMobile()));
            // 分发系统唯一id
            custInfo.setDistributeId(-1L);
            custInfo.setChannelSource(json.getString("code"));
            // 分发系统分过来的时间
            custInfo.setDistributeTime(new Date());
            logger.info("线索接收API请求转换：{}", custInfo.toString());
            // 客户申请信息前置检查
            Map<String, Object> checkResult = custInfoService.checkCustInfo(custInfo, logger);
            if (MapUtils.getIntValue(checkResult, "errorNo", -1) != 0) {
                setCode(-1);
                setMsg(MapUtils.getString(checkResult, "errorInfo", ""));
                return JSON.toJSONString(getResult());
            }
            logger.info("线索接收API：重复标识{}", isRepeat);
            if (isRepeat == 1) {
                CustInfo inParams = new CustInfo();
                inParams.setMd5val(custInfo.getMd5val());
                List<CustInfo> custInfos = custInfoService.selectCustInfoList(inParams);
                CustInfo lastCust = custInfos.get(0);
                // 设置重复标识
                custInfo.setRepeatFlag(lastCust.getEmpId() == null ? "1" : "2");
                custInfo.setLastRemarkTime(new Date());
                if (lastCust.getEmpId() != null) {
                    SysUser lastUser = iSysUserService.selectUserById(lastCust.getEmpId());
                    if (TypeConstant.FLAG_NO.equals(lastUser.getDelFlag())) {
                        // 原客户经理有效则分给原客户经理
                        if (custInfoService.dealCustReplay(custInfo, lastCust.getId(), lastUser, logger)) {
                            setCode(0);
                            setMsg("线索接收成功");
                            return JSON.toJSONString(getResult());
                        }
                    }
                }
            } else {
                custInfo.setRepeatFlag("0");
            }

            // 随机分配
            Long[] orgIds = custInfoService.getOrgIdsByCity(custInfo.getCity());
            boolean isSucceed = custInfoService.dealCustRandomly(custInfo, orgIds, true, false, logger);
            if (isSucceed) {
                setCode(0);
                setMsg("线索接收成功");
                if (StringUtils.isNotBlank(custInfo.getRemark())) {
                    // 自动生成一条备注
                    CustCommentRecord record = new CustCommentRecord();
                    record.setCustId(custInfo.getId());
                    record.setEmpId(null);
                    record.setEmpName("系统自动备注");
                    record.setRemark(custInfo.getRemark());
                    record.setType(1L);
                    record.setType2(1L);
                    record.setCreateTime(new Date());

                    custCommentRecordService.insertCustCommentRecord(record);
                }
            } else {
                setCode(-1);
                setMsg("线索接收API请求申请异常");
            }
        } catch (Exception e) {
            logger.info("线索接收API请求异常：", e.getMessage());
            setCode(-1);
            setMsg("api请求异常：" + e.getMessage());
        } finally {
            logger.info("线索接收API请求结果：code={}，msg = {}", code, msg);
        }
        return JSON.toJSONString(getResult());
    }


    /**
     * 获取post的请求参数
     *
     * @return
     */
    public String getRequestBoday() {
        HttpServletRequest request = (HttpServletRequest) ServletUtils.getRequest();
        InputStream inputStream;
        String strResponse = "";
        try {
            inputStream = request.getInputStream();
            String strMessage = "";
            BufferedReader reader;
            reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            while ((strMessage = reader.readLine()) != null) {
                strResponse += strMessage;
            }
            reader.close();
            inputStream.close();
        } catch (IOException e) {

        }
        return strResponse;
    }
}
